#!/bin/bash -eu
#
# Copyright 2021 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

source /opt/c2d/c2d-utils || exit 1

readonly opencart_folder="/var/www/html/store"

#######################################
# Awaits for host and port be ready.
# Arguments:
#   Target Hostname.
#   Target Port.
#   Timeout expected, 300s by default.
#######################################
function wait_for_port() {
  local -r host="$1"
  local -r port="$2"
  local -r timeout="${3:-300}"

  timeout --preserve-status "${timeout}" bash -c "until echo > /dev/tcp/${host}/${port}; do sleep 2; done"
  if [[ "$?" -ne 0 ]]; then
    exit 1
  fi
}

#######################################
# Creates a user for Mattermost application in MYSQL database.
# Arguments:
#   MySQL Hostname.
#   MySQL Database Name.
#   MySQL Username to be created.
#   MySQL Password for username created.
#######################################
function setup_mysql_user() {
  local -r db_user="$1"
  local -r db_password="$2"
  local -r db_name="$3"

  mysql -u root -e "CREATE USER '${db_user}'@'localhost' IDENTIFIED BY '${db_password}';"
  mysql -u root -e "GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES ON ${db_name}.* TO '${db_user}'@'localhost' IDENTIFIED BY '${db_password}';";
  mysql -u root -e "FLUSH PRIVILEGES"
}

#######################################
# Setup OpenCart Installer.
#######################################
function setup_opencart_installer() {
  local -r src_installer_folder="/usr/src/opencart"

  cp -rf "${src_installer_folder}/upload" "${opencart_folder}"
  cp -f "${src_installer_folder}/composer.json" "${opencart_folder}/composer.json"

  cd "${opencart_folder}"
  composer install --no-interaction
  rm -rf system/storage/vendor
  composer update --no-interaction
}

#######################################
# Install OpenCart initial database
# Arguments:
#   MySQL Username.
#   MySQL Password.
#   MySQL Database name.
#   OpenCart admin username.
#   OpenCart admin password.
#   OpenCart admin email.
#   OpenCart site url.
#######################################
function install_opencart_db() {
  local -r db_user="$1"
  local -r db_password="$2"
  local -r db_name="$3"
  local -r admin_user="$4"
  local -r admin_password="$5"
  local -r email="$6"
  local -r url="$7"

  cd "${opencart_folder}"
  php install/cli_install.php install \
    --db_hostname localhost \
    --db_username "${db_user}" \
    --db_password "${db_password}" \
    --db_database "${db_name}" \
    --db_driver mysqli \
    --db_port 3306 \
    --username "${admin_user}" \
    --password "${admin_password}" \
    --email "${email}" \
    --http_server "${url}"
}

#######################################
# Prepare Apache and PHP configuration files.
#######################################
function prepare_apache_and_php() {
  cd "${opencart_folder}"

  # Enable OpenCart specific php configs
  mv php.ini /etc/php/7.4/apache2/conf.d/opencart.ini

  # Enable store htaccess
  mv -f .htaccess.txt .htaccess

  # Create apache root htaccess
  echo "RedirectMatch 302 ^\/(?!.*store).* /store/" > ../.htaccess

  # Disable default apache website
  a2dissite 000-default
}

#######################################
# Fix OpenCart storage location.
#######################################
function fix_storage_location() {
  cd "${opencart_folder}"
  mv /var/www/html/store/system/storage /var/www/storage
  sed -i "s/DIR_SYSTEM \. 'storage\//'\/var\/www\/storage\//g" config.php
  sed -i "s/DIR_SYSTEM \. 'storage\//'\/var\/www\/storage\//g" admin/config.php
}

#######################################
# Fix OpenCart PHP dependencies folder.
#######################################
function fix_vendor_modules() {
  cd "${opencart_folder}"

  local -r vendor_dir="/var/www/storage/vendor"
  local config_contents="$(jq -r \
    --arg vendorDir "${vendor_dir}" \
    '.config."vendor-dir" = $vendorDir' "composer.json")"

  echo "${config_contents}" > "composer.json"
  mkdir -p "${vendor_dir}"
  composer install --no-interaction
}
